package com.shiro.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.*;

/**
 * @ClassName: ShiroConfig
 * @Description:
 * @Author: Administrator
 * @Date: 2021/3/22 0022 下午 15:11
 */
@Configuration
public class ShiroConfig {

    /**
     * ShiroFilterFactoryBean
     * @param defaultSecurityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultSecurityManager") DefaultSecurityManager defaultSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        // 设置安全管理器
        bean.setSecurityManager(defaultSecurityManager);
        // 添加Shiro的内置过滤器
        /**
         * anon: 无需认证就可以访问
         * authc: 必须认证才能访问
         * user: 用户拦截器，用户已经身份验证/记住我登录的都可
         * perms: 权限授权拦截器，验证用户是否拥有所有权限
         * roles: 角色授权拦截器，验证用户是否拥有所有角色
         */
        Map<String,String> filterMap = new LinkedHashMap<>();

        // 授权
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/update","perms[user:update]");

        // 拦截
        filterMap.put("/user/*","authc");
        bean.setFilterChainDefinitionMap(filterMap);
        // 设置登陆请求
        bean.setLoginUrl("/toLogin");

        // 未授权页面
        bean.setUnauthorizedUrl("/noauth");


        return bean;
    }

    /**
     * DefaultSecurityManager
     * @param realm
     * @return
     */
    @Bean
    public DefaultWebSecurityManager getDefaultSecurityManager(@Qualifier("userRealm") UserRealm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 管理UserRealm
        securityManager.setRealm(realm);
        return securityManager;
    }

    /**
     * 创建Reaml对象，自定义
     * @return
     */
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    // 整个ShiroDialect: 用于整合Shiro thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
